import 'package:flutter/material.dart';

import 'test_first_page.dart';
import 'test_second_page.dart';

class TestMainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => TestMainPageState();
}

class TestMainPageState extends State<TestMainPage> {
  int currentPage = 0;
  int currentIndex = 0;
  PageController _pageController = PageController(
  );
  List<Widget> _pages = <Widget>[
    TestFirstPage(),
    TestSecondPage(),
  ];
  List<Map<String, String>>  bottomItems = <Map<String, String>>[
    {
      'title': '客户',
      'icon': 'ic_customer.png',
      'active_icon': 'ic_customer_selected.png',
    },
    {
      'title': '我的',
      'icon': 'ic_mine.png',
      'active_icon': 'ic_mine_selected.png',
    },
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        backgroundColor: Colors.white,
        type: BottomNavigationBarType.fixed,
        currentIndex: currentIndex,
        selectedFontSize: 12,
        unselectedFontSize: 12,
        selectedItemColor: Color(0xFFBB2E2D),
        unselectedItemColor: Color(0xFFC9C9C9),
        onTap: indexChanged,
        items: bottomItems
            .map((item) => generateBottomBarItem(item))
            .toList(),
      ),
      body: WillPopScope(
        onWillPop: () {
          print("哈哈哈");
          if (currentPage > 0) {
            print("哈哈哈:$currentPage");
            _pageController.jumpToPage(0);
          }
          print('不要划拉');
          return Future.value(false);
        },
        child: PageView.builder(
          itemBuilder: (context, index) {
            return _pages[index];
          },
          controller: _pageController,
          onPageChanged: (index) {
            currentPage = index;
            currentIndex = index;
            setState(() {

            });
          },
          itemCount: _pages.length,
        ),
      ),
    );
  }

  BottomNavigationBarItem generateBottomBarItem(Map<String, String> item){
    return BottomNavigationBarItem(
      icon: Image.asset(
        'images/bottom_item/${item['icon']}',
        height: 18,
        fit: BoxFit.fitHeight,
      ),
      activeIcon: Image.asset(
        'images/bottom_item/${item['active_icon']}',
        height: 18,
        fit: BoxFit.fitHeight,
      ),
      label: item['title'],
    );
  }

  void indexChanged(int index) {
    if(currentIndex == index)
      return;
    currentIndex = index;
    currentPage = index;
    setState(() {
      _pageController.animateToPage(
          index,
        //动画曲线
        curve: Curves.ease,
        //滚动时间
        duration: Duration(milliseconds: 200),
      );
    });
  }
}
